﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OA.Service.SDK
{
    public class Client
    {
        private System.Net.WebClient client;

        public Client(string ServerUrl, string UserName, string Password)
        {
            this.ServerUrl = ServerUrl;
            this.UserName = UserName;
            this.PassWord = Password;
            client= new System.Net.WebClient();
            client.Encoding = System.Text.Encoding.UTF8;
        }

        /// <summary>
        /// 服务地址
        /// </summary>
        public string ServerUrl { get; set; }

        /// <summary>
        /// 调用接口账号
        /// </summary>
        public string UserName { get; set; }

        /// <summary>
        /// 调用接口密码(大写32位MD5)
        /// </summary>
        public string PassWord { get; set; }       

        /// <summary>
        /// 执行请求
        /// </summary>
        public T Execute<T>(Model.BaseReqeust<T> req) where T :Model.BaseResponse, new()
        {
            T ret = null;
            try
            {
                req.Head.UserName = UserName;
                req.Head.PassWord = PassWord;
                var reqxml = Common.SerializationHelper.Serialize(req);
                var resultXml = client.UploadString(ServerUrl, reqxml);
                ret = Common.SerializationHelper.DeSerialize<T>(resultXml);
            }
            catch (Exception e)
            {
                ret = new T()
                {
                    Code = 99,
                    Message = e.Message
                };
            }
            return ret;
        }
    }
}
